package com.cmj.service.impl;

import com.cmj.Utils.BeanCopyUtils;
import com.cmj.Utils.JwtUtil;
import com.cmj.Utils.RedisCache;
import com.cmj.domain.ResponseResult;
import com.cmj.domain.entity.LoginUser;
import com.cmj.domain.entity.User;
import com.cmj.domain.vo.BlogUserLoginVo;
import com.cmj.domain.vo.UserInfoVo;
import com.cmj.service.BlogLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

/**
 * 这是注释
 */
@Service
public class BlogLoginServiceImpl implements BlogLoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    /***
     * 登录服务
     * @param user 用户信息
     * @return 登录
     */
    @Override
    public ResponseResult login(User user) {

        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        //这里会自动调用UserDetailsServiceImpl中的loadUserByUsername方法（一般验证用户登录情况）
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //判断认证是否通过
        if (authenticate == null){
            throw new RuntimeException("用户名或密码错误！");
        }

        //获取userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userid = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userid);

        //把用户信息存入redis
        redisCache.setCacheObject("bloglogin:"+userid,loginUser);

        //把token和userinfo封装 返回
        //把User转换成UserInfoVo
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
        BlogUserLoginVo vo = new BlogUserLoginVo(jwt,userInfoVo);

        return ResponseResult.okResult(vo);
    }

    /***
     * 退出登录实现
     * @return 操作结果
     */
    @Override
    public ResponseResult logout() {
        //获取token 解析获取userid
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //获取userid
        Long userId = loginUser.getUser().getId();
        //删除redis中的用户信息
        redisCache.deleteObject("bloglogin:"+userId);
        return ResponseResult.okResult();
    }
}
